package by.cooker.chat.logic;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

/**
 * @author cooker
 */
public class Client
{
	private static Client client = null;

	private static Socket socket;

	/**
	 * Get <code>Client</code> class instance.
	 * 
	 * @return instance.
	 */
	public synchronized static Client getClient()
	{
		if (client == null)
		{
			client = new Client();
		}
		return client;
	}

	/**
	 * Connect.
	 * 
	 * @param server
	 *            - server name or server IP address.
	 * @param port
	 *            - server port.
	 * @param login
	 *            - user login.
	 * @param password
	 *            - user password.
	 * @throws IOException
	 *             - if connect problem.
	 */
	public synchronized void connect(User user) throws IOException
	{
		socket = new Socket(user.getHost(), user.getPort());
		PrintStream stream = new PrintStream(socket.getOutputStream());
		byte[] msg =
		{ 0x03, 0x04, 0x0D };
		stream.write(msg);
		stream.flush();
		stream.println(user.getLogin());
		stream.println(user.getPassword());

		String line = "/join " + user.getChannel();
		stream.println(line);
	}

	/**
	 * Get socket.
	 * 
	 * @return socket.
	 */
	public synchronized Socket getSocket()
	{
		return socket;
	}
}
